<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <title>NearFi</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .banner {
            text-align: center;
            margin-bottom: 10px;
            margin-top: 10px;
        }
        .banner img {
            max-width: 60%;
            height: auto;
        }
        .login, .main {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 300px;
        }
        .login h2, .main h2 {
            margin: 0 0 10px;
        }
        .login input[type="password"], .login input[type="submit"], .main input[type="checkbox"] {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            box-sizing: border-box;
        }
        .main label {
            display: block;
            margin: 10px 0;
        }
        .main input[type="submit"] {
            margin-top: 20px;
        }
        footer {
            text-align: center;
            margin-bottom: 10px;
            margin-top: 10px;
            font-size: 14px;
        }
        .full-width-option {
            width: 100%;
            box-sizing: border-box;
        }
        .full-width-button {
            padding: 10px 20px;
            width: 100%;
            box-sizing: border-box;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .divider {
            border-bottom: 1px solid #ccc;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="login" id="login-form">
        <div class="banner">
            <img src="banner.png" alt="Banner Image">
        </div>
        <div class="divider"></div>
        <h2>Ingrese su contraseña</h2>
        <input type="password" id="password" placeholder="Contraseña">
        <input type="submit" value="Login" class="full-width-button" onclick="login()">
        <div class="divider"></div>
        <footer>
            &copy; 2024 Getbit Systems. All rights reserved.
        </footer>
    </div>
    <div class="main" id="main-form" style="display: none;">
        <div class="container">
            <div class="banner">
                <img src="banner.png" alt="Banner Image">
            </div>
            <div class="divider"></div>
            <h2>Configuración</h2>
            <form id="config-form" onsubmit="saveSettings(event)">
                <label for="network-name">Nombre de la red (SSID)</label>
                <input type="text" id="network-name" class="full-width-option" name="network-name" required pattern="[a-zA-Z0-9_-]{4,64}" title="El nombre de la red solo puede contener letras, números, guiones y guiones bajos, y debe tener entre 4 y 64 caracteres.">
    
                <label for="max-clients">Número máximo de clientes</label>
                <input type="number" id="max-clients" class="full-width-option" name="max-clients" min="0" max="15" required>
                
                <label for="max-connection-time">Tiempo máximo de conexión (minutos)</label>
                <input type="number" id="max-connection-time" class="full-width-option" name="max-connection-time" min="0" max="65535" required>
            
                <input type="submit" value="Guardar" class="full-width-button">
            </form>
        </div>
        <div class="divider"></div>
        <footer>
            &copy; 2024 Getbit Systems. All rights reserved.
        </footer>
    </div>

    <script>
        let otp = '';
        let currentSettings = '';

        function login() {
            const password = document.getElementById('password').value;

            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                },
                body: password
            })
            .then(response => {
                if (response.status === 200) {
                    return response.text();  // Expect the OTP as plain text
                } else {
                    throw new Error('Invalid password');
                }
            })
            .then(receivedOtp => {
                otp = receivedOtp;  // Assign the received OTP to the global variable
                document.getElementById('login-form').style.display = 'none';
                document.getElementById('main-form').style.display = 'block';
                loadConfig();
            })
            .catch(error => {
                console.error('Error during login:', error);
                alert('An error occurred during login. Please try again.');
            });
        }

        function saveSettings(event) {
            event.preventDefault();
            const maxClients = document.getElementById('max-clients').value;
            const maxConnectionTime = document.getElementById('max-connection-time').value * 60;
            const networkName = document.getElementById('network-name').value;

            const namePattern = /^[a-zA-Z0-9_-]{4,31}$/;
            if (!namePattern.test(networkName)) {
                alert('El nombre de la red solo puede contener letras, números, guiones y guiones bajos, y debe tener entre 4 y 64 caracteres.');
                return;
            }

            if (maxClients < 1 || maxClients > 15) {
                alert('El número máximo de clientes debe estar entre 1 y 15.');
                return;
            }

            if (maxConnectionTime < 1 || maxConnectionTime > 65535) {
                alert('El tiempo máximo de conexión debe estar entre 1 y 1000 minutos.');
                return;
            }

            const newSettings = `${maxClients},${maxConnectionTime},${networkName}`;
            if (newSettings === currentSettings) {
                alert('No hay cambios en la configuración.');
                return;
            }

            fetch('/set_settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain',
                    'Otp': otp
                },
                body: newSettings
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    alert('Ajustes guardados exitosamente');
                    currentSettings = newSettings;
                } else {
                    alert('Error guardando la configuración');
                }
            })
            .catch(error => {
                console.error('Error saving config:', error);
                alert('Error guardando la configuración');
            });
        }

        function loadConfig() {
            fetch('/get_settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain',
                    'Otp': otp
                },
            })
            .then(response => response.text())
            .then(data => {
                let values = data.split(',');
                document.getElementById('max-clients').value = values[0];
                document.getElementById('max-connection-time').value = values[1] / 60;
                document.getElementById('network-name').value = values[2];
                currentSettings = data;
            })
            .catch(error => console.error('Error loading config:', error));
        }
    </script>
</body>
</html>
